import React, { useState, useEffect, useCallback, useMemo } from 'react'

import { message, Table, Image, Button, Space, Tag, Row, Col, Popconfirm, Rate, Input, Select, Upload } from 'antd'
import { DeleteOutlined, FormOutlined, PlusOutlined, ImportOutlined, ExportOutlined, SearchOutlined, UploadOutlined } from '@ant-design/icons'
import { useNavigate, useSearchParams } from 'react-router-dom'
import axios from 'axios'

import { connect } from 'react-redux'
const { Option } = Select;

import request, { baseUrl } from '../../../utils/request'
// import { useStore, useSelector } from 'react-redux'

//请求数据链接
// import axios from 'axios'
// export const baseUrl = 'http://120.76.247.5:2001'

// const request = axios.create({   
//     baseURL: baseUrl + '/api',
// })


function List(props) {

    console.log('11111', props);
    const navigate = useNavigate();
    // 分页功能
    const [urlParams, setUrlParams] = useSearchParams()
    const [params, setParams] = useState({
        // 解决数据类型为string引起的bug
        page: Number(urlParams.get('page')) || 1,
        size: Number(urlParams.get('size')) || 10
    })
    const [total, setTotal] = useState(0)
    // 设置初始数据
    const [datalist, setDatalist] = useState([]);
    // 分页功能的配置
    const pagination = {
        total,
        current: params.page,
        pageSize: params.size,
        size: 'small',
        onChange(page, size) {
            setParams({
                page,
                size
            })

            setUrlParams({
                page,
                size
            })
        }
    }



    //获取总的列表数据
    const getData = async () => {
        // controller = new AbortController()
        const { data } = await request.get('/iq', {
            params
        })
        console.log('面试题总的数据：', data);
        setDatalist(data.data.result)
        setTotal(data.data.total)
    }

    //删除列表项功能保留
    const removeItem = useCallback(async (id) => {
        const { data } = await request.delete('/iq/' + id)
        console.log(data);
        if (data.status === 200) {
            message.success('数据删除成功')
            // 刷新页面方案一：重新请求数据
            getData()

            // 刷新页面方案二：修改state达到刷新的效果
            // setDatalist(datalist.filter(item => item._id != id))
        }
    }, [datalist])


    //批量删除功能保留
    const [selectIds, setSelectIds] = useState([])
    const removeItems = useCallback(async () => {
        if (selectIds.length === 0) {
            return message.warning('请选择删除的数据');
        }
        const { data } = await request.delete('/iq', {
            data: {
                ids: selectIds
            }
        })
        if (data.status === 200) {
            message.success('数据删除成功')
            getData()
        }
    }, [selectIds])







    const columns = [
        // //自定义单元格内容
        // render: (text, record, index) => {
        //     // text: 当前列数据(dataIndex对应的数据，如无dataIndex,text与record一致)
        //     // record: 当前行数据
        //     // index: 当前索引值
        {
            title: '#',
            key: '_id',
            render(text, record, index) {
                return index + 1
            }
        },
        {
            title: '面试题',
            dataIndex: 'question',
            render(text, record, index) {
                // console.log('record', record);
                const { answer, hot, category, difficulty } = record
                return (
                    <>
                        <h3>{text}</h3>
                        {/* <p> */}
                        {
                            category ? <Button size='small' className='w_space' onClick={categoryEdit}>{category}</Button> : <Button className='w_space' size='small' type="dashed" onClick={categoryEdit}>未分类 </Button>
                        }
                        <span className='w_space'>{hot}浏览 ·</span>
                        <span className='w_space'>{answer}回答 ·</span>
                        <span>难度：{<Rate disabled defaultValue={difficulty} allowHalf />}</span>
                        {/* </p> */}
                    </>
                )
            }
        },
        {
            title: 'tags',
        },
        {
            title: '审核',
            dataIndex: 'checked',
            width: 80,
            render(text, record, index) {
                return text == false ? <Button size='small' onClick={audit}>未审核</Button> : <Button size='small' type='primary' ghost onClick={audit}>已审核</Button>
            }
        },
        {
            title: '时间',
            dataIndex: 'addtime',
            width: 120,
            render(text, record, index) {
                return text.slice(0, 10)
            }
        },
        {
            title: '操作',
            dataIndex: '_id',
            width: 100,
            render(id) {
                return (
                    // <React.Fragment>
                    <Space>
                        <Button ghost type='primary' icon={<FormOutlined />} size="small" onClick={editItem.bind(null, id)}></Button>
                        <Popconfirm
                            title="确认删除"
                            onConfirm={removeItem.bind(null, id)}
                        >
                            <Button danger icon={<DeleteOutlined />} size="small"></Button>

                        </Popconfirm>
                    </Space>
                )
            }
        },
    ]
    //复选框功能
    const rowSelection = {
        onChange(selectedRowKeys) {
            console.log('selectedRowKeys=', selectedRowKeys)
            setSelectIds(selectedRowKeys)
        }
    }







    // 跳转到添加页面
    const addItem = useCallback(() => {
        navigate('/manage/question/add')
    }, [])
    // 跳转到编辑页面
    const editItem = useCallback((id) => navigate('/manage/question/' + id), [])
    // 跳转到审核页面
    const audit = useCallback((id) => navigate('/manage/question/audit'), [])
    // 跳转分类列表页面
    const categoryEdit = useCallback((id) => navigate('/manage/category/list'), [])



    // 搜索框功能
    const changeValue = async (value) => {
        console.log(value, 'jjjjjjjj');
        setUrlParams({ keyword: value })

        const { data } = await request.get('/search',
            {
                params: {
                    keyword: value,
                }

            })
        // console.log('搜索的数据', data);
        setDatalist(data.data.result)


    }



    // 导入导出功能
    const toExport = async () => {
        const { data } = await request.post('/iq/export', {

            userid: props.user._id,
            ids: selectIds
        })
        console.log(data, "dd");
        window.open(data)
    }


    // 初始化
    useEffect(() => {
        getData()


    }, [params])

    return (
        <div>
            <div>
                <Input.Group compact style={{ marginBottom: '20px' }}>
                    <Select defaultValue="React" width={100}>
                        {
                            datalist.map((item) => {
                                return <Option key={item._id} value={item.category}>{item.category}</Option>

                            })
                        }
                    </Select>
                    <Input.Search
                        onSearch={changeValue}
                        style={{
                            width: '60%',
                        }}
                    />
                </Input.Group>
            </div>


            <Row gutter={20}>
                <Col span={4}>
                    <Button type='primary' icon={<PlusOutlined />} onClick={addItem}>添加</Button>
                </Col>
                <Col span={6} >
                    <Space>

                        <Button icon={<ExportOutlined />} onClick={toExport}>导出</Button>


                        {/* <Upload action="http://120.76.247.5:2001/api/iq/import"
                            headers={{
                                Authorization: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyaWQiOiI2MzQ5NzQ2MDhmZDdmOTM1ZDgwYzdmMzgiLCJpYXQiOjE2NjU4NDM2NDEsImV4cCI6MTY2NTg1MDg0MX0.Heoui44TmPXaOjyDpAXwFO2eWr-OUu3ShX0nF-8Y3iw",
                                ['Access-Control-Allow-Origin']: '*'
                            }}
                            accept=".doc,.docx, .xlsx" >
                            <Button icon={<ImportOutlined />}>导入</Button>
                        </Upload> */}
                    </Space>

                </Col>
                <Col span={14} className='text-right'>
                    <Popconfirm
                        title="确认删除"
                        onConfirm={removeItems}
                    >
                        <Button danger size='small' icon={<DeleteOutlined />}>批量删除</Button>
                    </Popconfirm>
                </Col>
            </Row>
            <Table
                style={{ marginTop: 20 }}
                rowKey="_id"
                rowSelection={rowSelection}
                columns={columns}
                dataSource={datalist}
                pagination={pagination}
            />
        </div>

    )
}


// 映射Redux状态到组件的props
const mapStateToProps = function (state) {
    return {
        user: state.userInfo
    }
}



List = connect(mapStateToProps)(List)

export default List;